import Dep from './dep'

//消息发布者
export default class Observer {
    constructor(value) {
        if (!value || typeof value !== 'object') {
            return
        }
        this.value = value
        this.walk(value)
    }

    walk(value) {
        //递归观察属性
        Object.keys(value).forEach(key => this.convert(key, value[key]))
    }

    convert(key, val) {
        defineReactive(this.value, key, val)
    }
}

export function defineReactive(obj, key, val) {
    let dep = new Dep()
    Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        //访问data属性时发布
        get: function () {
            Dep.target && dep.addSub(Dep.target);
            return val
        },
        //设置data属性时通知观察者，并且观察新的属性
        set: newVal => {
            if (newVal === val) {
                return
            }
            val = newVal
            dep.notify()
        }
    })
}
